package com.kmvc.message.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.kmvc.message.activity.MessageApplication;
import com.kmvc.message.service.DownloadService;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.widget.Toast;

public class DownloadFile {
	private NotificationManager manager;
	private Notification notification;
	private PendingIntent PIntent;
	private long nSDFreeSize;
	/**
	 * 
	 * @param URL
	 *            下载地址
	 * @param pname
	 *            文件名
	 * @param context
	 *            上下文
	 * @param name
	 *            软件名
	 */
	@SuppressWarnings("deprecation")
	public void DownLoad(final String URL, final String pname,
			final Context context, final String name,final String SavaPath) {

		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			StatFs statFs = new StatFs(Environment
					.getExternalStorageDirectory().getPath());
			// 获取SDcard上的总BLOCK总数
		//	long nTotalBlocks = statFs.getBlockCount();
			// 获取SDcard上每个block的size
			long nBlockSize = statFs.getBlockSize();
			// 获取可供程序使用的Block的数量
			long nAvailaBlock = statFs.getAvailableBlocks();
			// 获取剩下的所有Block的数量(包括预留的一般程序无法使用的块)
			//long nFreeBlock = statFs.getFreeBlocks();
		    // 计算 SDCard 剩余大小MB   
		    nSDFreeSize = nAvailaBlock * nBlockSize / 1024 / 1024;		    
			File destDir = new File(Environment.getExternalStorageDirectory()
					.toString() +SavaPath);
			if(nSDFreeSize<10)
			{
				Toast.makeText(
						context,
						"检测到您的SD卡剩余存储不足" + nSDFreeSize+"M,请释放部分存储空间" +
								"或更换更大容量的存储卡",Toast.LENGTH_LONG).show();
			}
			if (!destDir.exists()) {
				destDir.mkdirs();
			}

			if (pname.contains(".apk")) {
				try {
					manager = (NotificationManager) context
							.getSystemService(Context.NOTIFICATION_SERVICE);
					// 构建一个通知对象
					notification = new Notification(
							android.R.drawable.stat_sys_download,
							name + "开始下载", System.currentTimeMillis());
					notification.setLatestEventInfo(context, "下载中", name
							+ "正在下载中", null);
					notification.flags = Notification.FLAG_AUTO_CANCEL;

					manager.notify(0, notification);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			new Thread() {
				public void run() {
					HttpClient client = new DefaultHttpClient();
					HttpGet get = new HttpGet(URL);
					HttpResponse response;
					try {
						response = client.execute(get);
						HttpEntity entity = response.getEntity();
						long length = entity.getContentLength();
												 
						InputStream is = entity.getContent();
						FileOutputStream fileOutputStream = null;
						if (is != null) {
							File file = new File(
									Environment.getExternalStorageDirectory()
											+ SavaPath, pname);
							fileOutputStream = new FileOutputStream(file);
							byte[] buf = new byte[1024];
							int ch = -1;
							int upcount = 0;
							int downloadcount = 0;
							while ((ch = is.read(buf)) != -1) {
								fileOutputStream.write(buf, 0, ch);
								downloadcount = downloadcount + ch;// 时时获取下载到的大小
								if (upcount == 0
										|| (downloadcount * 100 / length - 5) >= upcount) {// 每次增长5%
									upcount += 5;
									// pBar.setProgress(count);// 进度条当前的值
									if (pname.contains(".apk")) {
										try {
											notification.setLatestEventInfo(
													context, "下载中", name
															+ upcount + "%",
													null);
											manager.notify(0, notification);
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								}
							}
						}
						fileOutputStream.flush();
						if (fileOutputStream != null) {
							fileOutputStream.close();
						}
						if (pname.contains(".apk")) {

							Intent intent = new Intent(Intent.ACTION_VIEW);
							intent.setDataAndType(Uri.fromFile(new File(
									"mnt/sdcard/KMVC_MESSAGE/", pname)),
									"application/vnd.android.package-archive");
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

							PIntent = PendingIntent.getActivity(context, 0,
									intent, 0);
							Notification notification = new Notification(
									android.R.drawable.stat_sys_download_done,
									name + "下载完成", System.currentTimeMillis());
							notification.setLatestEventInfo(context, "下载完成",
									name + "下载完成,点击安装", PIntent);
							notification.defaults = Notification.DEFAULT_SOUND;// 添加声音提示
							// audioStreamType的值必须是AudioManager中的值，代表响铃的模式
							notification.audioStreamType = android.media.AudioManager.ADJUST_LOWER;
							manager.notify(0, notification);
							downok(pname);// 下载完成
							// postdown(MobileInfo.getIMSI(context),pname.replace(".apk",""),name);

						}
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				private void downok(final String pname) {
					Intent intent = new Intent(context, DownloadService.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.stopService(intent);

					if (pname.contains(".apk")) {
						// postdown(MobileInfo.getIMSI(context),pname.replace(".apk",""),name);
						new Thread() {
							public void run() {
								try {

									Intent intent = new Intent(
											Intent.ACTION_VIEW);
									intent.setDataAndType(Uri
											.fromFile(new File(
													"mnt/sdcard/KMVC_MESSAGE/",
													pname)),
											"application/vnd.android.package-archive");
									intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// Context调用startActivity需要加这句
									context.startActivity(intent);

								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}.start();
					}
					else 
					{
						MessageApplication app=(MessageApplication)((Activity)context).getApplication();
					    app.DownLoadList.remove(pname);
					    app.DownLoadList.put(pname, true);
					}

				}

			}.start();
		}

		else {
			Toast.makeText(context, "没有找到SD卡,请插入SD卡", Toast.LENGTH_LONG).show();
		}

	}

}
